define(['app', 'json2'], function(app, JSON2) {
    app.controller('AddMockController', function($http, xContext, $uibModalInstance, xDialog) {
        var self = this;
        self.module = '';
        self.type = 'folder';
        self.parent = '';
        self.folder = '';
        self.file = '';
        self.data = '';

        self.init = function() {
            self.module = xContext.module;
            if (xContext.treeNode.root) {
                self.parent = '/';
            } else {
                self.parent = xContext.treeNode.parent + '/' + xContext.treeNode.name;
            }
        }

        self.save = function(valid) {
            if (valid) {
                var folder = self.parent;
                if (self.type == 'folder') {
                    folder = self.parent + '/' + self.folder;
                }
                $http.post('/mock/data/save', {
                    created: true,
                    module: self.module,
                    type: self.type,
                    folder: folder,
                    file: self.file + '.json',
                    data: '{}'//JSON2.trim(self.data)
                }).then(function(response) {
                    if (response.data) {
                        $uibModalInstance.close({
                            name: (self.type == 'file' ? self.file + '.json' : self.folder),
                            leaf: (self.type == 'file'),
                            parent: (self.parent.root ? '' : self.parent)
                        });
                    } else {
                        if (self.type == 'file') {
                            xDialog.alert('提示信息', '您创建的文件已存在，请更改为其它名称！');
                        } else {
                            xDialog.alert('提示信息', '您创建的文件夹已存在，请更改为其它名称！');
                        }
                    }
                });
            }
        }

        self.cancel = function() {
            $uibModalInstance.dismiss();
        }
    });
});
